<<template>
	<el-dialog :title="title" :visible.sync="show" width="85%" :close-on-click-modal='false'>
    <el-row :gutter="10">
      <el-col :span="6">
        <div class="grid-content"> 
          <div style="margin: 10px;">
            <el-input v-model="like.value" placeholder="请输入段落名搜索" style="width: 168px;"></el-input>
            <el-button type="primary" v-on:click="getParagraphList">查询</el-button>
          </div>
          <ul class="cus_list">
            <li v-for="item in list" :key="item.id" @click="select(item)" :class="{cur: item.id == selectParagraph.id }">
              {{item.name}}
            </li>
          </ul>
        </div>
      </el-col>
      <el-col :span="10">
        <div style="position: relative" class="grid-content sec">     
          <div style="margin-bottom: 10px;">
            <label>文章标的：</label>
            <el-select v-model="category" placeholder="请选择文章标的">
              <el-option
                v-for="item in typeOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </div>
          <div style="margin-bottom: 10px;">
            <label>文章用途：</label>
            <el-select v-model="channel" multiple placeholder="请选择文章用途">
              <el-option
                v-for="item in channelOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </div>
          <div style="margin-bottom: 10px;">
            <label>文章名称：</label>
            <el-input
              placeholder="请输入文章名称"
              v-model="name"
              style="width: 216px;">
            </el-input>
          </div>
          <div style="margin-bottom: 10px;">
            <label style="">文章标题：</label>
            <div style="display: inline-block;">
              <ParagraphCard v-if="titleParagraph" :data="titleParagraph" :index="0" @remove="removeTitle"></ParagraphCard>
              <i class="el-icon-plus" @click="addTitle"></i>
            </div>
          </div>
          <div style="margin-top: 30px;position: relative;">
            <label style="position: absolute; left:0; top: 10px;">文章内容：</label>
            <div style="display: inline-block; margin-left: 80px;" class="clearfix">
              <i class="el-icon-plus" style="margin-bottom: 10px;" @click="addParagraph"></i>
              <div v-for="(item, index) in paragraphList" :key="item.id">
                <!-- <label>文章段落{{index+1}}</label> -->
                <ParagraphCard :data="item" :index="index" @remove="removeParagraph"></ParagraphCard>
              </div>
            </div>
          </div>
        </div>
      </el-col>
      <el-col :span="8">
        <div class="grid-content">
          <!--<div style="margin: 15px;">
            <label>发布日期：</label>
             <el-select v-model="dateType" placeholder="请选择日期" style="width: 193px;">
              	<el-option label="全部" :value="1"></el-option>
              	<el-option label="交易日" :value="2"></el-option>
              	<el-option label="非交易日" :value="3"></el-option>
            </el-select>
            <el-time-picker style="margin-left: 73px; margin-top: 10px;" v-model="time" placeholder="任意时间点"></el-time-picker>
          </div>-->
          
	      	<el-form label-width="90px" style="margin: 10px;">
			  	<el-form-item label="发布日期：">
	     			<el-select v-model="dateType" placeholder="请选择日期">
		              	<el-option label="全部" :value="1"></el-option>
		              	<el-option label="交易日" :value="2"></el-option>
		              	<el-option label="非交易日" :value="3"></el-option>
	        		</el-select>
			  	</el-form-item>
			  	<el-form-item v-if="chooseDate" label="具体日期：">
		         	<el-select v-model="dateTypeDtl" multiple placeholder="请选择日期">
		     		    <el-option
				      		v-for="item in options"
					      	:key="item.value"
					      	:label="item.label"
					      	:value="item.value">
					    </el-option>
		            </el-select>
			  	</el-form-item>
		  	  	<el-form-item label="发布时间：">
				    <el-time-picker v-model="time" placeholder="任意时间点"></el-time-picker>
		  		</el-form-item>
		  	</el-form>
        </div>
      </el-col>
    </el-row>
    <div v-if="showPreview" class="pre-wrap">
      <div v-html="previewHTML"></div>
    </div>
	  <div slot="footer" class="dialog-footer">
	    <el-button @click="show = false">取 消</el-button>
      <el-button @click="preview">{{previewText}}</el-button>
      <el-button @click="save">确定</el-button>
	  </div>
	</el-dialog>
</template>
<script>
import api from "../../../api/api";
import ParagraphCard from "../phrase/PhraseCard.vue";
import typeOptions from '../../../common/typeOptions';
export default {
  props: {
    id: null
  },
  created() {
    this.getParagraphList();
    this.getDetail();
  },
  components: {
    ParagraphCard
  },
  computed: {
    title() {
      return this.id ? "编辑文章" : "新建文章";
    }
  },
  data() {
    return {
      show: true,
      atomId: null,
      list: [],
      selectParagraph: {},
      phrases: [],
      titleParagraph: null,
      paragraphList: [],
      previewText: "预览",
      showPreview: false,
      previewHTML: "",
      dateType: 1,
      chooseDate:false,
      dateTypeDtl:[],
      channel: '',
      time: "",
      like: {
        key: "name",
        value: ""
      },
      channelOptions: [
        {
          label: "灯塔文章",
          value: 1
        },
        {
          label: "银河文章",
          value: 2
        },
        {
          label: "中信建投",
          value: 3
        }     
      ],
      typeOptions: typeOptions,
      category: 1,
      name: "",
      options:[{value: 1, label: '星期一'}, {value: 2, label: '星期二'}, {value: 3, label: '星期三'}, {value: 4, label: '星期四'}, {value: 5, label: '星期五'}]
    }
  },
  methods: {
    getParagraphList() {
      let filters = [
        {
          type: "1",
          key: "status",
          value: 1
        }
      ];
      let para = {
        currentPage: 0,
        pageNumb: 1000,
        wheres: JSON.stringify(filters),
        like: JSON.stringify(this.like),
        order: "id",
        tableName: "paragraph"
      };
      api
        .getList(para)
        .then(res => {
          if (res.ret == 0) {
            this.list = res.data.dataList;
          }
        })
        .catch(e => {
          this.$message({
            type: "error",
            message: "获取短语列表失败"
          });
        });
    },
    getDetail() {
      if (this.id) {
        api
          .getDataByID({
            tableName: "article",
            id: this.id
          })
          .then(res => {
            if (res.ret == 0) {
              let template = res.data.template;
              let publish_day = res.data.publish_day;
              let data = JSON.parse(template);
              this.name = res.data.name;
              this.category = res.data.category;
              this.dateType = res.data.publish_date;
              if(publish_day){  //null, ""
              	let arr = publish_day.split(',');
              	this.dateTypeDtl = arr.map(item => { return item * 1});
              }else{
              	this.dateTypeDtl = [];
              }
              this.channel = res.data.channel.split(',');
              for (let index = 0; index < this.channel.length; index++) {
                this.channel[index] = Number(this.channel[index]);
              }
              if (res.data.publish_time) {
                let arrs = res.data.publish_time.split(":");
                this.time = new Date();
                this.time.setHours(arrs[0]);
                this.time.setMinutes(arrs[1]);
                this.time.setSeconds(arrs[2]);
              }
              this.titleParagraph = data.title && data.title[0];
              this.paragraphList = data.contents;
              // (this.name = res.data.name), (this.content = res.data.template);
            } else {
              this.$message({
                type: "error",
                message: "查询文章信息失败！"
              });
            }
          })
          .catch(e => {
            this.$message({
              type: "error",
              message: "查询文章信息失败！"
            });
          });
      }
    },
    select(item) {
      this.selectParagraph = item;
    },
    addTitle() {
      if (this.selectParagraph.id) {
        this.titleParagraph = this.selectParagraph;
      }
    },
    removeTitle(item, index) {
      this.titleParagraph = null;
    },
    addParagraph() {
      if (this.selectParagraph.id) {
        this.paragraphList.push(this.selectParagraph);
      }
    },
    removeParagraph(item, index) {
      this.paragraphList.splice(index, 1);
    },
    save() {
      if (this.name.length > 0 && this.time) {
        let form = {};
        if (this.id) {
          form.id = this.id;
        }
        form.name = this.name;
        form.category = this.category;
        form.channel = this.channel.toString();
        let template = {};
        if (this.titleParagraph && this.titleParagraph.id) {
          template.title = [
            {
              id: this.titleParagraph.id,
              name: this.titleParagraph.name,
              status: this.titleParagraph.status
            }
          ];
        }
        template.contents = [];
        this.paragraphList.forEach(element => {
          let obj = {
            id: element.id,
            name: element.name,
            status: element.status
          };
          template.contents.push(obj);
        });
        form.template = JSON.stringify(template);
        form.publish_date = this.dateType;
        if(this.chooseDate){
    		if(this.dateTypeDtl.length == 5){
        		form.publish_day = "";
        	}else{
        		form.publish_day = this.dateTypeDtl.join();
        	}
        }else{
        	form.publish_day = "";
        }
        if (this.time) {
          	form.publish_time = Date.format(this.time, "HH:mm:ss");
        }
        api.addOrEditSubmit({
            tableName: "article",
            form: form
         }).then(res => {
            if (res.ret == 0) {
              this.$message({
                type: "success",
                message: "添加或者更新文章成功！"
              });
              this.show = false;
              this.$emit("refresh");
              this.publishSchedule(res.data);
            } else {
              this.$message({
                type: "error",
                message: "添加或者更新文章失败！"
              });
            }
          })
          .catch(e => {
            this.$message({
              type: "error",
              message: "添加或者更新文章失败！"
            });
          });
      } else {
        this.$message({
          type: "success",
          message: "文章名称和发布时间不能为空"
        });
      }
    },
    publishSchedule(data) {
      let form = {
        time: Date.format(this.time, "HH:mm:ss"),
        id: this.id || data.insertId
      };
      api.publishSchedule({ form: form }).then(res => {
        if (res.ret == 0) {
          this.$message({
            type: "success",
            message: "添加或者更新文章成功！"
          });
          this.show = false;
          this.$emit("refresh");
        }
      });
    },
    preview() {
      	if (this.showPreview) {
	        this.showPreview = false;
	        this.previewText = "预览";
	        return;
      	}
      	let form = {};
      	form.name = this.name;
      	let template = {};
      	if (this.titleParagraph && this.titleParagraph.id) {
	        template.title = [
	          	{
		            id: this.titleParagraph.id,
		            name: this.titleParagraph.name,
		            status: this.titleParagraph.status
	          	}
	        ];
      	}
      	template.contents = [];
      	this.paragraphList.forEach(element => {
	        let obj = {
	          	id: element.id,
	          	name: element.name,
	          	status: element.status
	        };
	        template.contents.push(obj);
      	});
      	form.template = JSON.stringify(template);
      	api.getPreviewArticle({
          	form: form
       	}).then(res => {
          	if (res.ret == 0) {
	            console.log(res.data);
	            this.previewHTML = res.data;
	            this.showPreview = true;
	            this.previewText = "关闭预览";
          	} else {
	            this.$message({ type: "error", message: "预览文章失败" });
          	}
        }).catch(e => {
          	this.$message({ type: "error", message: "无法预览文章" });
        });
    }
  },
  watch: {
    show(val) {
      if (!val) {
        this.$emit("closedialog");
      }
    },
    dateType(val){
    	if(val == 2){
    		this.chooseDate = true;
    	}else{
    		this.chooseDate = false;
    	}
    }
  }
}
</script>
<style>
.cus_dialog .el-dialog {
  width: 75%;
}
</style>


